#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# # author : cypro666
# # date   : 2015.08.01
# # wrapper of Gauss Mixture methods in sklearn
import sys, json, time
import numpy as np
from threading import Thread
from sklearn import mixture

from magic3.utils import Timer
from magic3.filesystem import *
add_sys_path(grand_dir(__file__))

from skt.base import MethodBase
from skt.utils import _normalize, make_options


class GMM(MethodBase):
    def __init__(self, parameters={}):
        super().__init__(parameters)

    @property
    def name(self): return 'GMM'

    def output(self, model):
        self.Log('output')
        super().output()
        extra = {}

        # try:    extra['covars'] = [list(i) for i in model.covars_]
        # except: pass

        try:    extra['weights'] = [float(i) for i in model.weights_]
        except: pass

        try:    extra['means'] = [list(v) for v in model.means_]
        except: pass

        try:    extra['converged'] = model.converged_
        except: pass

        fn = self.json_name()
        json.dump(extra, open(fn, 'w'), indent=4)

    def execute(self):
        self.read_input()
        self._normalize(False, self._param['normalize'])

        if self._param['n_components'] not in set(range(1, 20)):
            self._param['n_components'] = 1

        if self._param['n_iter'] < 10:
            self._param['n_iter'] = 10

        if self._param['n_init'] < 1:
            self._param['n_init'] = 1

        if self._param['min_covar'] <= 1E-6:
            self._param['min_covar'] = 1E-6

        if self._param['tol'] <= 1E-6:
            self._param['tol'] = 1E-6

        self.save_parameters()

        model = mixture.GMM(covariance_type='full',
                            init_params='wmc',
                            params='wmc',
                            n_components=self._param['n_components'],
                            n_init=self._param['n_init'],
                            n_iter=self._param['n_iter'],
                            min_covar=self._param['min_covar'],
                            tol=self._param['tol'],
                            random_state=True)

        model.fit(self._train)

        self._results = model.predict(self._testing)
        self.output(model)

    def run(self, timeout):
        t = Thread(target=self.execute)
        t.start()
        t.join(timeout)
        if t.is_alive():
            self.Log('timeout!')
        self.Log('exit')


if __name__ == '__main__':
    opts = [('train_file', 'str', []),
            ('label_file', 'str', []),
            ('testing_file', 'str', []),
            ('results_file', 'str', []),
            ('log_file', 'str', []),
            ('normalize', 'choice', ['0', '1', '2']),
            ('n_components', 'int', []),
            ('n_init', 'int', []),
            ('n_iter', 'int', []),
            ('min_covar', 'float', []),
            ('tol', 'float', [])]

    parameters = make_options(opts)

    timer = Timer()

    GMM(parameters).run(300)

    if __debug__:
        print('elapsed:', timer)






